import { Op } from "sequelize";
import sys_role from "../../model/sys_role";

/*
 * @Author: fishroom
 * @Date: 2022-10-14 13:57:23
 * @LastEditTime: 2023-01-03 13:45:07
 * @FilePath: \koa\app\server\Sys\SysRoleServer.ts
 */
class SysRoleServer {
  async getRoleList(limit: number = 10, offset: number = 0, params: object | any) {
    let role_id = params.role_id ? Number(params.role_id) : undefined;
    delete params.role_id;
    let obj = [];
    if (role_id) {
      obj.push({ role_id });
    } else if (params.role_name) {
      obj.push({
        role_name: {
          [Op.substring]: params.role_name,
        },
      });
    }
    return await sys_role.findAndCountAll({
      where: {
        [Op.and]: obj,
      },
      offset,
      limit,
    });
  }
  async addRole(role: any) {
    if (role.role_id) delete role.role_id;
    return await sys_role.create({ ...role });
  }
  async deleteRoleById(role_id: number) {
    if (!role_id) return;
    await sys_role.destroy({
      where: {
        role_id,
      },
    });
  }
  async updateRoleById(role: any) {
    if (!role.role_id) return new Error("没有id");
    let role_id = role.role_id;
    delete role.id;
    sys_role.update(
      { ...role },
      {
        where: {
          role_id,
        },
      }
    );
  }
}

export default new SysRoleServer();
